import 'package:flutter/material.dart';

class LyricLine {
  final Duration timestamp;
  final String text;

  LyricLine(this.timestamp, this.text);

  static List<LyricLine> parse(String lrcContent) {
    final List<LyricLine> lyrics = [];
    final RegExp regex = RegExp(r'\[(\d{2}):(\d{2})\.(\d{2,3})\](.*)');

    for (var line in lrcContent.split('\n')) {
      final match = regex.firstMatch(line);
      if (match != null) {
        final minutes = int.parse(match.group(1)!);
        final seconds = int.parse(match.group(2)!);
        final milliseconds = int.parse(match.group(3)!.padRight(3, '0'));
        final text = match.group(4)!.trim();

        if (text.isNotEmpty) {
          lyrics.add(LyricLine(
            Duration(
              minutes: minutes,
              seconds: seconds,
              milliseconds: milliseconds,
            ),
            text,
          ));
        }
      }
    }

    lyrics.sort((a, b) => a.timestamp.compareTo(b.timestamp));
    return lyrics;
  }
}

class LyricsView extends StatefulWidget {
  final String lyrics;
  final Duration position;
  final Duration duration;

  const LyricsView({
    super.key,
    required this.lyrics,
    required this.position,
    required this.duration,
  });

  @override
  State<LyricsView> createState() => _LyricsViewState();
}

class _LyricsViewState extends State<LyricsView> {
  late List<LyricLine> _lyrics;
  final ScrollController _scrollController = ScrollController();
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _lyrics = LyricLine.parse(widget.lyrics);
  }

  @override
  void didUpdateWidget(LyricsView oldWidget) {
    super.didUpdateWidget(oldWidget);

    if (oldWidget.lyrics != widget.lyrics) {
      _lyrics = LyricLine.parse(widget.lyrics);
      _currentIndex = 0;
    }

    // 更新当前行
    for (int i = 0; i < _lyrics.length; i++) {
      if (i == _lyrics.length - 1 ||
          (widget.position >= _lyrics[i].timestamp &&
              widget.position < _lyrics[i + 1].timestamp)) {
        if (_currentIndex != i) {
          _currentIndex = i;
          _scrollToCurrentLine();
        }
        break;
      }
    }
  }

  void _scrollToCurrentLine() {
    if (_lyrics.isEmpty) return;

    final itemHeight = 40.0; // 每行歌词的高度
    _scrollController.animateTo(
      _currentIndex * itemHeight,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_lyrics.isEmpty) {
      return const Center(child: Text('暂无歌词'));
    }

    return ListView.builder(
      controller: _scrollController,
      itemCount: _lyrics.length,
      itemBuilder: (context, index) {
        final isCurrentLine = index == _currentIndex;

        return Container(
          height: 40,
          alignment: Alignment.center,
          child: Text(
            _lyrics[index].text,
            style: TextStyle(
              fontSize: isCurrentLine ? 16 : 14,
              color: isCurrentLine ? Colors.blue : Colors.grey,
              fontWeight: isCurrentLine ? FontWeight.bold : FontWeight.normal,
            ),
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
}
